# -*- coding:utf-8 -*-
# File Name:mysql.py
# Author:jing
# Date:2018/12/18

from interface.resource import Resource
from model.mongo_model.resource_info import ResourceInfo
from util.date_util import get_date
from util.port_util import get_possible_port
from util.str_util import get_random_string, get_random_kube_name

__author__ = 'jing'


class Mysql(Resource):
    def after_release_kube(self):
        # todo clean files
        pass

    @classmethod
    def create_info(cls, resource_data):
        uid = resource_data.get('uid')
        container_port = 3306
        env = cls._get_env(resource_data)

        info = ResourceInfo(
            apply_date=get_date(),
            container_port=container_port,
            env=env,
            image=resource_data.get('image') or 'mysql:5.6',
            user_id=uid,
            host_port=get_possible_port(),
            resource_type=cls.get_resource_type(),
            args=['--character-set-server={}'.format(
                resource_data.get('encoding') or 'utf8mb4'
            )],
            resource_name=resource_data.get('resource_name'),
            limits=resource_data.get('limits'),
            requests=resource_data.get('requests')
        )
        cls.save_resource_info(info)

    @classmethod
    def _get_env(cls, resource_data):
        uid = resource_data.get('uid')
        mysql_user = resource_data.get('MYSQL_USER') or '{}-{}'.format(uid, get_random_string(5))
        env = {
            'MYSQL_DATABASE': resource_data.get('MYSQL_DATABASE') or '{}_db'.format(uid),
            'MYSQL_USER': mysql_user,
            'MYSQL_PASSWORD': resource_data.get('MYSQL_PASSWORD') or get_random_string(10),
            'MYSQL_RANDOM_ROOT_PASSWORD': get_random_string(10)
        }
        return env

    @classmethod
    def get_resource_type(cls):
        return 'mysql'

    def get_config(self):
        return {
            'args': self.resource_info.args
        }

    def check(self) -> bool:
        return True  # todo check select 1
